<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" xmlns:head="http://www.w3.org/1999/html">
<head th:include="public/public_css::public_css ('品项数分析')" />

<body style="background-color: #f2f2f2;">
<div class="layui-fluid larry-wrapper">
    <div class="layui-card">
        <div class="layui-row layui-col-space30">
            <div class="layui-col-xs24">
                <form class="layui-form   layui-card-header-auto" id="searchForm" >   <!--layui-card-header-->

                    <!--<input type="hidden" id="nytime" name="nytime">-->
                    <!--<input type="hidden" id="fpsj_end" name="fpsj_end">-->
                    <div class="layui-collapse" lay-filter="test">
                        <div class="layui-colla-item">
                            <h2 class="layui-colla-title">品项数分析</h2>
                            <div class="layui-colla-content" style="float: left;">
                                <label  data-title>产品分类</label>
                                <div class="layui-inline">
                                    <div class="layui-input-inline">
                                        <!--<input type="text" name="zdwsl" id="zdwsl" lay-verify="required" autocomplete="off" placeholder="请输入补货上限" value="1" class="layui-input" style="width: 120px">-->
                                        <select lay-ignore="lay-ignore" class="js-data-example-zl"  multiple="multiple" name="zlids" style="width: 193px;height: 3rem;border-radius: 1px">
                                        </select>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-colla-content" style="float: left;">
                                <label  data-title>产品名称</label>
                                <div class="layui-inline">
                                    <div class="layui-input-inline">
                                        <!--<input type="text" name="zdwsl" id="zdwsl" lay-verify="required" autocomplete="off" placeholder="请输入补货上限" value="1" class="layui-input" style="width: 120px">-->
                                        <select lay-ignore="lay-ignore" class="js-data-example-mc" name="hpids" multiple="multiple"  style="width: 193px"></select>

                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <div class="layui-input-block">
                                    <!--<button class="layui-btn" lay-submit  lay-filter="demo1" >立即提交</button>   &lt;!&ndash;lay-submit=""&ndash;&gt;-->
                                    <a id="save" class="layui-btn">保存</a>
                                    <button type="reset" class="layui-btn layui-btn-primary" onclick="queryTable()">重置</button>
                                </div>
                            </div>
                        </div>
                    </div>

                </form>
                <div class="row">
                    <div class="col-xs-6">
                        <div style="padding: 15px">
                            <form class="form-horizontal" role="form" id="details_form">
                                <div class="form-group" style="display: none">
                                    <div class="col-sm-8">

                                    </div>
                                </div>
                                <div id="tree"></div>
                            </form>
                        </div>
                    </div>
                </div>
                <!--列表-->
                <section id="tablesec" style="display: none" class="panel panel-padding layui-card-body" >
                    <div class="pro">
                        <table id="dataTable"class="table text-nowrap" width="100%" >
                        </table>
                    </div>
                </section>
            </div>
        </div>
    </div>
</div>
</body>

<div th:include="public/public_js::public_js"></div>
<script>
    var idsarr = [];
    var temp = new Object();//一个中间变量用来传递参数
    $(function () {
        console.log("开始啦。。。");
        var tree = function () {
            $.ajax({
                type: "POST",
                url: "/zxsswms/wmsorderchannel/list",
                dataType: "JSON",
                async: false,
                success: function (data) {
                    console.log('dadddd',data);
                    //将数据添加到省份这个下拉框里面
                    var treedata = treeDataFormat(data);
                    console.log(treedata);
//                    var trees = {};
//                    var treess = [];
//                    trees.text = "销售系统";
//                    trees.nodes = treedata;
//                    treess.push(trees);
//                    console.log(trees);

//                    var resultMap = eval(data);
//                    var map={};
//                    map.mc="销售系统";
//                    map.children=resultMap;
//                    map.nodes=resultMap;
//                    var maps=[];
//                    maps.push(map);
//                    maps.forEach(function (e) {//遍历集合
//                        serializ(e);//把集合的每一项放到序列化方法中序列化
//                    });
                    //选中父节点时，选中所有子节点
                    function getChildNodeIdArr(node) {
                        console.log('node',node);
                        var ts = [];
                        console.log('ts',ts);
                        if (node.nodes) {
                            console.log('if');
                            for (x in node.nodes) {
                                ts.push(node.nodes[x].nodeId);
                                if (node.nodes[x].nodes) {
                                    var getNodeDieDai = getChildNodeIdArr(node.nodes[x]);
                                    for (j in getNodeDieDai) {
                                        ts.push(getNodeDieDai[j]);
                                        }
                                    }
                                }
//                                console.log('fufu',fu);
                            } else {
                            ts.push(node.nodeId);
//                            console.log('else',ts);
//                            console.log('else,node',node);
                            }
                        return ts;
                        }
                    // 选中所有子节点时，选中父节点 取消子节点时取消父节点
                    function setParentNodeCheck(node) {
                        var parentNode = $("#tree").treeview("getNode", node.parentId);
                        if (parentNode.nodes) {
                            var checkedCount = 0;
                            for (x in parentNode.nodes) {
                                if (parentNode.nodes[x].state.checked) {
                                    checkedCount ++;
                                } else {
                                    break;
                                }
                            }
                            if (checkedCount == parentNode.nodes.length) {  //如果子节点全部被选 父全选
                                $("#tree").treeview("checkNode", parentNode.nodeId);
                                setParentNodeCheck(parentNode);
                            }else {   //如果子节点未全部被选 父未全选
                                $('#tree').treeview('uncheckNode', parentNode.nodeId);
                                setParentNodeCheck(parentNode);
                            }
                        }
                    }
                    // 取消父节点时 取消所有子节点
                    function setChildNodeUncheck(node) {
                        if (node.nodes) {
                            var ts = [];    //当前节点子集中未被选中的集合
                            for (x in node.nodes) {
                                if (!node.nodes[x].state.checked) {
                                    ts.push(node.nodes[x].nodeId);
                                } else if (node.nodes[x].nodes) {
//                                    alert('else,if');
                                    var getNodeDieDai = node.nodes[x];
                                    console.log(getNodeDieDai);
                                    for (j in getNodeDieDai) {
                                        if (!getNodeDieDai.state.checked) {
                                            ts.push(getNodeDieDai[j]);
                                        }
                                    }
                                }
                            }
                        }
                        return ts;
                    }
                    $('#tree').treeview(
                        {//树结构初始化，具体参数查阅bootstrap-treeview中文api
                        color: "#428bca",
                        levels: 2, // 初始收缩
//                        selectedBackColor: false,
                        showBorder: true,
                        showCheckbox: true,    //这里之所以写1，是因为我引得js源码里定义1为true
                        multiSelect: 0, //这里之所以写1，是因为我引得js源码里定义1为true    //多选
                        data: treedata,
                        hierarchicalCheck:true,
                        selectable: true,
                        highlightSelected: true,
                        onNodeChecked: function(event, node) { //选中节点
                            var selectNodes = getChildNodeIdArr(node); //获取所有子节点
                            console.log('selectNodes',selectNodes);
                            if (selectNodes) { //子节点不为空，则选中所有子节点
                                $('#tree').treeview('checkNode', [selectNodes, { silent: true }]);
                                }
//                            var parentNode = $("#tree").treeview("getNode", node.parentId);
                            setParentNodeCheck(node);
                            $('#tree').prop('checked',true);
                        },
                        onNodeUnchecked: function(event, node) { //取消选中节点
                            var selectNodes = setChildNodeUncheck(node); //获取未被选中的子节点
                            var childNodes  = getChildNodeIdArr(node); //获取未被选中的子节点
                            if (selectNodes && selectNodes.length===0) { //有子节点且未被选中的子节点数目为0，则取消选中所有子节点
                                console.log("反选");
                                $('#tree').treeview('uncheckNode', [childNodes, { silent: true }]);
                            }
                            // 取消节点 父节点取消
//                            var parentNode = $("#tree").treeview("getNode", node.parentId);  //获取父节点
//                            var selectNodes = getChildNodeIdArr(node);
                            setParentNodeCheck(node);
//                            if (selectNodes) { //子节点不为空，则取消选中所有子节点
//                                $('#tree').treeview('uncheckNode', [selectNodes, { silent: true }]);
//                              }
                        },
                });
                },
                error: function () { alert("Error"); }
            });
        }
        var init =function () {
            tree();
        }
        init()//初始化
    })
    //序列化方法 将ajax的数据序列化为树型结构
    function serializ(e,level) {
        console.log('e',e);
        console.log('level',level);
        e.text = e.mc;//bootstrap-treeview只显示名为text的属性
        //添加 增、改、删按钮
//        e.text +="<div style='float: right'>" +
//            "<button class =\" button button-primary button-tiny button-box\" name = \""+ e.id+"\"  onclick='addfunction(this)'>" +
//            "<i class=\" fa fa-plus\"></i>" +
//            "</button>" +
//                /*  "<button class =\" button button-action button-tiny button-box\" name = \""+ e.id+"\" style=\"margin-left: 3px\" onclick='editfunction(this)'>" +
//                 "<i class=\" fa fa-edit\"></i>" +
//                 "</button>" +
//                 "<button class =\" button button-caution button-tiny button-box\" name = \""+ e.id+"\" style=\"margin-left: 3px\" onclick='deletefunction(this)'>" +
//                 "<i class=\" fa fa-remove\"></i>" +
//                 "</button>" +*/
//            "</div>";
        if(level === null){//如果第一次进入序列化方法给他一个level属性来标记等级
            e.level = 1;
        }else {
            e.level += 1;//如果不是第一级 那么当前level+1
        }
        if(e.children !=null , e.children!=""){//如果当前节点有子节点就把子节点也序列化直到全部节点序列化完毕
            e.children.forEach(function (e) {
                serializ(e,level);
            })
            e.nodes = e.children;//他的子节点只认nodes
        }else {
            e.last = true ;
        }
    }

    function treeDataFormat(data) {
        var arr = [];
        for (var i = 0; i < data.length; i++) {
            var  Is = {};
            Is.text = data[i].mc;
            Is.id = data[i].id;
            if (data[i].children.length > 0) {
                Is.nodes = treeDataFormat(data[i].children);
            }
            arr.push(Is);
        }
        return arr;
    }

    var ajaxdata;

    //	回车查询
    document.onkeydown = function(event) {
        e = event ? event : (window.event ? window.event : null);
        if (e.keyCode == 13) {
            //执行的方法
            $('#search_button').click();
        }
    };
    $(function () {
        $(".moreBtn").on("click",function () {
            $(".moreSearch").toggle();
        })
    });
    layui.use(['list','layer','zzpUtils','jquery','laydate'],function () {
        var zzpUtils= layui.zzpUtils,
            $ = layui.jquery,
            form = layui.form,
            laydate = layui.laydate;
        // 年月选择器
        laydate.render({
            elem: '#test3',
            type: 'month',
        });
//        laydate.render({
//            elem: '#test5'
//            ,theme: '#20a0ff'
//        })
        //select2 产品分类
        var cpfl;
        $('.js-data-example-zl').select2({
            tags: true,
            tokenSeparators: [',', ' '],
            closeOnSelect: false,
            ajax: {
                url: '/zxsswms/statistics/goodsType',
                dataType: 'json',
                type: 'POST',
                contentType: "application/json",
                data: function (params) {
                    var query = {
                        mc: params.term
                    };
                    return JSON.stringify(query);
                },
                processResults: function (data) {
                    cpfl= [];
                    if(data){
                        for (var i=0;i<data.rows.length;i++){
                            cpfl.push({id:data.rows[i].id,text:data.rows[i].mc});
                        }
                    }
                    console.log('arr',cpfl);
                    return {
                        results: cpfl
                    };
                },
                cache: true,
            },
            language: "zh-CN",
            placeholder: '请选择产品分类',
            allowClear: true,
        });
//      //select2 查产品名称
        $('.js-data-example-mc').select2({
            closeOnSelect: false,
            ajax: {
                url: '/zxsswms/statistics/seachGoods',
                dataType: 'json',
                type: 'POST',
                contentType: "application/json",
                data: function (params) {
                    var query = {
                        mc: params.term,
                        ids: $('.js-data-example-zl').val(),
                    };
                    return JSON.stringify(query);
                },
                processResults: function (data) {
                    var arr= new Array();
                    if(data){
                        for (var i=0;i<data.rows.length;i++){
                            arr.push({id:data.rows[i].id,text:data.rows[i].mc});
                        }
                    }
                    console.log(arr);
                    return {
                        results: arr
                    };
                },
                cache: true
            },
            language: "zh-CN",
            placeholder: '请选择产品名称',
            allowClear: true
        });
//        查询提交
        $('#save').click(function () {
            $('#tablesec').css('display', 'block');
            BiaoTou();
        });
//        form.on("submit(demo1)",function(data){
//            alert(1111);
////            console.log('datad',JSON.stringify(data.field));
////            console.log('提交', data.field);
//
//            return false;
//        });
        function BiaoTou () {
            var zlids;
            // 产品分类
            if ($('.js-data-example-zl').val() == null) {
                zlids = []
            } else {
                zlids = $('.js-data-example-zl').val();
            }
            // 产品名称
            var hpids;
            if ($('.js-data-example-mc').val() == null) {
                hpids = []
            } else {
                hpids = $('.js-data-example-mc').val();
            }
            var data = [];
            var treeids =  $('#tree').treeview('getChecked');
            if (treeids.length > 0) {
                treeids.forEach(item => {
//                                console.log('item', item.id);
                    idsarr.push(item.id);
                });
            } else {
                idsarr = []
            }
            console.log('idsarr', idsarr);
            $.ajax({
                //方法类型
                type: "POST",
                //scriptCharset: "utf-8",
                //几个参数需要注意一下
                async: false,
                url: "/zxsswms/statistics/goodsTypeStatisticsTitle" ,
                data: JSON.stringify({
                    "zlids": zlids,
                    "hpids": hpids,
                    "channeIds": idsarr,
                    "page":1,
                    "rows":10
                }),
                contentType:"application/json",
                success: function (returnValue){
                    data = returnValue
//                    console.log('打印data', JSON.stringify(data));
//                    ajaxdata.push({"field": '',
//                        "checkbox": true,
//                    });
                    // 异步获取要动态生成的列
                },
            });
            $.ajax({
                //方法类型
                type: "POST",
                //scriptCharset: "utf-8",
                //几个参数需要注意一下
                async: false,
                url: "/zxsswms/statistics/goodsTypeStatistics" ,
                data: JSON.stringify({
                    "zlids": zlids,
                    "hpids": hpids,
                    "channeIds": idsarr,
                    "page":1,
                    "rows":10
                }),
                contentType:"application/json",
                success: function (res){
                    obj = res
//                    console.log('打印data', JSON.stringify(data));
//                    ajaxdata.push({"field": '',
//                        "checkbox": true,
//                    });
                    // 异步获取要动态生成的列
                },
            });
            var arr = [];
            var obj = [];
            $.each(data.column, function (i, item) {
//                        console.log('item', item);
                arr.push({
                    "field": item.prop,
                    "title": item.label,
                });
            });
//            console.log('打印data下', JSON.stringify(data));
            ajaxdata = arr;
            console.log('打印arr',arr);
            console.log('打印obj',obj);
            $("#dataTable").bootstrapTable('destroy').bootstrapTable({
                columns: ajaxdata   ,//动态表头
                data: obj           // 获取数据
            });

        }

        var $table = zzpUtils.table({
            elem: '#dataTable',
            isApi: true,
            pagination:true,
            striped: true,
            columns: [],
        });

        //查询list

//        $(".inline-search-btn").on('click',function () {
//            zzpUtils.refreshTable("#table");
//        })
        /*顶部按钮多选启用*/
        $("#btn_qi").on('click', function () {
            var index = 0;
            var $rows = $table.bootstrapTable('getSelections');

        })
        // 重置
        window.queryTable = function () {
            location.reload();
//            var formdata = $("form").serializeArray();
//            var DATA = {};
//            console.log('formdata',formdata);
////            DATA.cjsj_start = "";
////            DATA.cjsj_end = "";
////            DATA.zt = "";
////            DATA.cpbm = "";
////            DATA.cplx = "";
////            DATA.cpmc = "";
//            DATA.page = 1;
//            DATA.rows = 10;
//            $('#dataTable').bootstrapTable('refresh',{
//                query: DATA
//            })
        }
    });
</script>
</html>